package com.slingshot.identitylibrary.api

import com.alibaba.fastjson.JSONObject
import com.slingshot.identitylibrary.BuildConfig
import okhttp3.MediaType
import okhttp3.Request
import okhttp3.RequestBody
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*
import java.util.Collections.sort

internal object CommonApi {

    private const val BASE_URL = BuildConfig.SLINGSHOT_BASE_URL

    private const val ID_CARD_FRONT = "$BASE_URL/icCard?side=front"

    private const val ID_CARD_BACK = "$BASE_URL/icCard?side=back"

    private const val FACE_DETECT = "$BASE_URL/faceDetect"

    fun extractIdCardFace(appId: String, appSecret: String, imageBase64: String): Request.Builder {
        return getRequestBuilder(appId, appSecret, imageBase64, ID_CARD_FRONT)
    }

    fun extractIdCardNationalEmblem(appId: String, appSecret: String, imageBase64: String): Request.Builder {
        return getRequestBuilder(appId, appSecret, imageBase64, ID_CARD_BACK)
    }

    fun faceDetect(appId: String, appSecret: String, imageBase64: String, imageBase64_id: String): Request.Builder {
        return getRequestBuilder(appId, appSecret, imageBase64,imageBase64_id, FACE_DETECT)
    }
    fun faceDetect(appId: String, appSecret: String, imageBase64: String): Request.Builder {
        return getRequestBuilder(appId, appSecret, imageBase64, FACE_DETECT)
    }
    private fun getRequestBuilder(appId: String, appSecret: String, imageBase64: String,url: String): Request.Builder {
        val ts = System.currentTimeMillis().toString()
        val lists: MutableList<String> = ArrayList()
        lists.add("appid$appId")
        lists.add("ts$ts")
        val sign = getSign(appSecret, lists)
        return Request.Builder()
            .url(url)
            .header("appid", appId)
            .header("sign", sign)
            .header("ts", ts)
            .post(getRequestBody(imageBase64))
    }

    private fun getRequestBuilder(appId: String, appSecret: String, imageBase64: String, imageBase64_id: String,url: String): Request.Builder {
        val ts = System.currentTimeMillis().toString()
        val lists: MutableList<String> = ArrayList()
        lists.add("appid$appId")
        lists.add("ts$ts")
        val sign = getSign(appSecret, lists)
        return Request.Builder()
            .url(url)
            .header("appid", appId)
            .header("sign", sign)
            .header("ts", ts)
            .post(getRequestBody(imageBase64,imageBase64_id))
    }

    private fun getRequestBody(imageBase64: String,imageBase64_id: String): RequestBody {
        val jsonObject = JSONObject()
        jsonObject["image"] = imageBase64
        jsonObject["idcardimage"] = imageBase64_id
        return RequestBody.create(MediaType.parse("application/json"), jsonObject.toJSONString())
    }

    private fun getRequestBody(imageBase64: String): RequestBody {
        val jsonObject = JSONObject()
        jsonObject["image"] = imageBase64
        return RequestBody.create(MediaType.parse("application/json"), jsonObject.toJSONString())
    }

    private fun getSign(secret: String, lists: List<String>): String {
        val sign: String
        sort(lists)
        var signBegin = secret
        for (i in lists.indices) {
            signBegin += lists[i]
        }
        signBegin += secret
        sign = getMD5(signBegin)
        return sign
    }

    private fun getMD5(`val`: String): String {
        var m: ByteArray? = null
        try {
            val md5: MessageDigest = MessageDigest.getInstance("MD5")
            md5.update(`val`.toByteArray())
            m = md5.digest() //加密
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return if (m != null) {
            getString(m)
        } else {
            ""
        }
    }

    private fun getString(b: ByteArray): String {
        val buf = StringBuilder()
        for (aB in b) {
            var a = aB.toInt()
            if (a < 0) a += 256
            if (a < 16) buf.append("0")
            buf.append(Integer.toHexString(a))
        }
        return buf.toString().toUpperCase(Locale.ROOT) //32位
    }
}